package cn.harry.cabinet.utils

import android.content.Context
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.os.Build

object VersionUtil {
	fun getVersionName(context: Context): String {
		return try {
			val info = getPackageInfoCompat(context)
			info?.versionName ?: ""
		} catch (e: Exception) {
			""
		}
	}

	fun getVersionCode(context: Context): Long {
		return try {
			val info = getPackageInfoCompat(context)
			if (info == null) 0L else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) info.longVersionCode else @Suppress("DEPRECATION") info.versionCode.toLong()
		} catch (e: Exception) {
			0L
		}
	}

	fun getFormattedVersion(context: Context, includeCode: Boolean = false, prefixV: Boolean = true): String {
		val name = getVersionName(context)
		val code = getVersionCode(context)
		val prefix = if (prefixV) "v" else ""
		return if (includeCode && code > 0) "$prefix$name ($code)" else "$prefix$name"
	}

	private fun getPackageInfoCompat(context: Context): PackageInfo? {
		return try {
			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
				context.packageManager.getPackageInfo(context.packageName, PackageManager.PackageInfoFlags.of(0))
			} else {
				@Suppress("DEPRECATION")
				context.packageManager.getPackageInfo(context.packageName, 0)
			}
		} catch (e: Exception) {
			null
		}
	}
}

